//
//  CQHomeTableViewController.m
//  01-OC微博
//
//  Created by 陈乾 on 15/10/25.
//  Copyright © 2015年 陈乾. All rights reserved.
//

#import "CQHomeTableViewController.h"
#import "UIBarButtonItem+CQBarButtonItem.h"
#import "CQTitleButton.h"
#import "CQCoverView.h"
#import "UIView+Frame.h"
#import "CQPopEnum.h"
#import "CQOneTableViewController.h"
#import "UIBarButtonItem+CQBarButtonItem.h"
#import "AFNetworking.h"
#import "CQAccount.h"
#import "CQAccountTool.h"
#import "MJExtension.h"
#import "CQStatus.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "CQHttpTool.h"

@interface CQHomeTableViewController ()<CQCoverViewDelegate>


@property (nonatomic, strong)  CQOneTableViewController *oneVC;
/**
 *  标题按钮
 */
@property (nonatomic, strong) CQTitleButton *titleButton;
/**
 *  保存了所有的微博模型的数组
 */
@property (nonatomic, strong) NSMutableArray *statusArr;
@property (nonatomic, strong) NSMutableArray *imageArr;

@end

@implementation CQHomeTableViewController

#pragma mark - 懒加载
-(CQOneTableViewController *)oneVC
{
    if (_oneVC == nil) {
        _oneVC = [[CQOneTableViewController alloc] init];
    }
    return _oneVC;
    
}

-(NSMutableArray *)statusArr {
    if (_statusArr == nil) {
        _statusArr = [NSMutableArray array];
    }
    return _statusArr;

}

//下拉刷新的图片数组
-(NSMutableArray *)imageArr {
    if (_imageArr == nil) {
        
        _imageArr = [NSMutableArray array];

        for (int i = 0; i< 30; i++) {
            NSString *imageName = [NSString stringWithFormat:@"ico_imsm_loading_stonehenge_000%.2d",i];
            UIImage *image = [UIImage imageNamed:imageName];
            [_imageArr addObject:image];
        }
    }
    return _imageArr;
}


#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏按钮
    [self setNavigationButton];
    
    
    //请求网络微博数据 用自动进入刷新状态
    [self loadNetworkStatus];
    //下拉刷新(带图片的)
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNetworkStatus)];
    //设置普通状态下的下拉刷新
    [header setImages:self.imageArr duration:3 forState:MJRefreshStateRefreshing];
    self.tableView.header = header;
    
    
    //上拉刷新(带图片的)
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreOldStatus)];
    //设置普通状态下的下拉刷新
    [footer setImages:self.imageArr duration:3 forState:MJRefreshStateRefreshing];
    self.tableView.footer = footer;
    
    
    
    
    
}
#pragma mark -加载微博旧的的数据
/**
 *  加载微博旧的的数据
 *
 */
- (void)loadMoreOldStatus {
    
    
    //创建请求类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //请求地址
    NSString *urlStr = @"https://api.weibo.com/2/statuses/friends_timeline.json";
    //access_token参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    //只要存在微博数据的前提下 才下拉刷新
    if (self.statusArr.count != 0) {
        //把最小的的微博数给他  他就返回更大id的微博 这写微博就是最新微博
        long long max = [[[self.statusArr lastObject] idstr] longLongValue] - 1;
        
        parameters[@"max_id"] = [NSString stringWithFormat:@"%lld",max];
        
    }
    parameters[@"access_token"] = [CQAccountTool loadAccount].access_token;
    
    //工具类封装的GET请求
     [CQHttpTool GET:urlStr parameters:parameters success:^(id responseObject) {
#warning 数据来源 记得一定要刷新表格 才有数据展示
         
         //结束上拉刷新
         [self.tableView.footer endRefreshing];
         
         //一个大的字典 里面装这一个字典数组
         NSArray *dictArr = responseObject[@"statuses"];
         //通过一个字典数组 来创建模型数组
         NSArray *statuses = [CQStatus objectArrayWithKeyValuesArray:dictArr];
         
         //把statuses中的元素一个一个添加到数组中
         [self.statusArr addObjectsFromArray:statuses];
         
         [self.tableView reloadData];
         
     } failure:^(NSError *error) {
         
     }];
    
    
    



}

#pragma mark -加载微博网络数据
/**
 *  加载微博网络数据
 *
 */
- (void)loadNetworkStatus {

  
    //创建请求类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //请求地址
    NSString *urlStr = @"https://api.weibo.com/2/statuses/friends_timeline.json";
    //access_token参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    //只要存在微博数据的前提下 才下拉刷新
    if (self.statusArr.count != 0) {
        //把最大的微博数给他  他就返回更大id的微博 这写微博就是最新微博
        parameters[@"since_id"] = [[self.statusArr firstObject] idstr];
        
    }
    
    
    parameters[@"access_token"] = [CQAccountTool loadAccount].access_token;
    
    //工具类隔离的网络框架
    [CQHttpTool GET:urlStr parameters:parameters success:^(id responseObject) {
#warning 数据来源 记得一定要刷新表格 才有数据展示
        
        //结束刷新
        [self.tableView.header endRefreshing];
        
        //一个大的字典 里面装这一个字典数组
        NSArray *dictArr = responseObject[@"statuses"];
        //通过一个字典数组 来创建模型数组
        NSArray *statuses = [CQStatus objectArrayWithKeyValuesArray:dictArr];
        
        
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
        [self.statusArr insertObjects:statuses atIndexes:indexSet];
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];

}

/**
 *  设置导航条上的按钮
 */
- (void) setNavigationButton{
    
    //左边按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_friendsearch"] highImage:[UIImage imageNamed:@"navigationbar_friendsearch_highlighted"] target:self action:@selector(friendsearch) forControlEvents:UIControlEventTouchUpInside];
    //右边按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_pop"] highImage:[UIImage imageNamed:@"navigationbar_pop_highlighted"] target:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    
    
    CQTitleButton *titleButton = [[CQTitleButton alloc] init];
    
    //设置三要素
    [titleButton setTitle:@"首页" forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateSelected];
    //取消高亮的 图片的调整
    titleButton.adjustsImageWhenHighlighted = NO;
    
    self.titleButton = titleButton;
    //监听方法
    [titleButton addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleButton;
    
}

#pragma mark - 回调方法
//朋友搜索方法
- (void)friendsearch
{
    
}
//点击左边的按钮
- (void)pop
{
    //先看有木有CQOneTableView.xib 有则加载
    //再看有木有CQOneTableViewController.xib
    //如果没有就创建一个几乎透明的view
    //这里可以直接init就行了
#warning  原因：init 底部会调用 initWithNibName： 方法
    CQOneTableViewController *oneVC = [[CQOneTableViewController alloc] init];
    
    [self.navigationController pushViewController:oneVC animated:YES];
    
}



//点击首页按钮
- (void)clickBtn:(CQTitleButton*)button
{
    //选中状态取反
    button.selected = !button.selected;
    //创建覆盖的view
    CQCoverView *coverView = [CQCoverView show];
    //设置代理
    coverView.delegate = self;
    //弹出pop菜单
    CGFloat popW = 200;
    CGFloat popX = (self.view.width - popW)*0.5;
    CGFloat popH = popW;
    CGFloat popY = 55;
    
    CQPopEnum *popEnum = [CQPopEnum showWithFrame:CGRectMake(popX, popY, popW, popH)];
    popEnum.contentView = self.oneVC.view;
    
}

//代理方法

- (void)coverView:(CQCoverView *)coverView
{

    [CQPopEnum hide];
    
    self.titleButton.selected = NO;
    

}

#pragma mark - Table view data source

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statusArr.count;

}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    //取模型
    CQStatus *status  = self.statusArr[indexPath.row];
    
    cell.textLabel.text = status.user.name;
    
    [cell.imageView sd_setImageWithURL:status.user.profile_image_url placeholderImage:[UIImage imageNamed:@"timeline_image_placeholder"]];
    cell.detailTextLabel.text = status.text;
    
    return cell;

}


@end
